<template>
  <div class="mortgage-calculator">
    <!-- 头部导航 -->
    <div class="detail-header">
      <div class="header-content">
        <button class="back-btn" @click="goBack">
          <i class="el-icon-arrow-left"></i>
        </button>
        <h2 class="page-title">房贷计算器</h2>
      </div>
    </div>

    <!-- 计算区域 -->
    <div class="calculator-container">
      <!-- 输入参数 -->
      <div class="input-section">
        <div class="section-header">
          <h3>贷款信息</h3>
        </div>
        
        <div class="input-group">
          <div class="input-item">
            <label>房屋总价 (万元)</label>
            <el-input-number 
              v-model="housePrice" 
              :min="0" 
              :max="10000" 
              :precision="1"
              :step="10"
              @change="calculateMortgage"
            ></el-input-number>
          </div>
          
          <div class="input-item">
            <label>首付比例 (%)</label>
            <el-slider 
              v-model="downPaymentPercent" 
              :min="20" 
              :max="70" 
              :marks="{20: '20%', 30: '30%', 40: '40%', 50: '50%', 60: '60%', 70: '70%'}"
              @change="calculateMortgage"
            ></el-slider>
            <div class="percent-display">{{ downPaymentPercent }}%</div>
          </div>
          
          <div class="input-item">
            <label>贷款金额 (万元)</label>
            <div class="loan-amount">{{ loanAmount.toFixed(1) }} 万元</div>
          </div>
          
          <div class="input-item">
            <label>贷款年限 (年)</label>
            <el-select v-model="loanYears" @change="calculateMortgage">
              <el-option 
                v-for="year in [5, 10, 15, 20, 25, 30]" 
                :key="year" 
                :label="year + '年'" 
                :value="year"
              ></el-option>
            </el-select>
          </div>
          
          <div class="input-item">
            <label>贷款利率 (%)</label>
            <el-input-number 
              v-model="interestRate" 
              :min="0" 
              :max="10" 
              :precision="2"
              :step="0.1"
              @change="calculateMortgage"
            ></el-input-number>
          </div>
          
          <div class="input-item">
            <label>还款方式</label>
            <el-radio-group v-model="repaymentMethod" @change="calculateMortgage">
              <el-radio label="equal-principal-interest">等额本息</el-radio>
              <el-radio label="equal-principal">等额本金</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>

      <!-- 计算结果 -->
      <div class="result-section">
        <div class="section-header">
          <h3>计算结果</h3>
        </div>
        
        <div class="result-cards">
          <div class="result-card">
            <div class="result-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="result-content">
              <div class="result-label">月供金额</div>
              <div class="result-value">{{ monthlyPayment }} 元</div>
            </div>
          </div>
          
          <div class="result-card">
            <div class="result-icon">
              <i class="el-icon-bank-card"></i>
            </div>
            <div class="result-content">
              <div class="result-label">总利息</div>
              <div class="result-value">{{ totalInterest }} 万元</div>
            </div>
          </div>
          
          <div class="result-card">
            <div class="result-icon">
              <i class="el-icon-coin"></i>
            </div>
            <div class="result-content">
              <div class="result-label">还款总额</div>
              <div class="result-value">{{ totalPayment }} 万元</div>
            </div>
          </div>
          
          <div class="result-card">
            <div class="result-icon">
              <i class="el-icon-s-data"></i>
            </div>
            <div class="result-content">
              <div class="result-label">首付金额</div>
              <div class="result-value">{{ downPaymentAmount }} 万元</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 还款计划表 -->
      <div class="schedule-section" v-if="paymentSchedule.length > 0">
        <div class="section-header">
          <h3>还款计划</h3>
          <el-button type="text" @click="toggleSchedule">
            {{ showSchedule ? '收起' : '展开' }}
            <i :class="showSchedule ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
          </el-button>
        </div>
        
        <transition name="fade">
          <div v-show="showSchedule" class="schedule-table">
            <el-table 
              :data="paymentSchedule.slice(0, 12)" 
              style="width: 100%"
              height="300"
            >
              <el-table-column prop="period" label="期数" width="80"></el-table-column>
              <el-table-column prop="monthlyPayment" label="月供" width="100"></el-table-column>
              <el-table-column prop="principal" label="本金" width="100"></el-table-column>
              <el-table-column prop="interest" label="利息" width="100"></el-table-column>
              <el-table-column prop="remaining" label="剩余本金" width="100"></el-table-column>
            </el-table>
            <div class="schedule-tip" v-if="paymentSchedule.length > 12">
              仅显示前12期，完整还款计划共{{ paymentSchedule.length }}期
            </div>
          </div>
        </transition>
      </div>

      <!-- 利率参考 -->
      <div class="rate-reference">
        <div class="section-header">
          <h3>利率参考</h3>
        </div>
        <div class="rate-cards">
          <div class="rate-card">
            <div class="rate-type">商业贷款基准利率</div>
            <div class="rate-value">4.20%</div>
          </div>
          <div class="rate-card">
            <div class="rate-type">公积金贷款基准利率</div>
            <div class="rate-value">3.10%</div>
          </div>
          <div class="rate-card">
            <div class="rate-type">LPR最新报价</div>
            <div class="rate-value">3.95%</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MortgageCalculator',
  data() {
    return {
      housePrice: 300, // 房屋总价（万元）
      downPaymentPercent: 30, // 首付比例
      loanYears: 30, // 贷款年限
      interestRate: 4.2, // 年利率（%）
      repaymentMethod: 'equal-principal-interest', // 还款方式
      showSchedule: false, // 是否显示还款计划
      paymentSchedule: [] // 还款计划表
    }
  },
  computed: {
    // 贷款金额（万元）
    loanAmount() {
      return this.housePrice * (100 - this.downPaymentPercent) / 100
    },
    // 首付金额（万元）
    downPaymentAmount() {
      return this.housePrice * this.downPaymentPercent / 100
    },
    // 月供金额
    monthlyPayment() {
      const monthlyRate = this.interestRate / 100 / 12
      const totalMonths = this.loanYears * 12
      
      if (this.repaymentMethod === 'equal-principal-interest') {
        // 等额本息
        if (monthlyRate === 0) return Math.round(this.loanAmount * 10000 / totalMonths)
        
        const monthlyPayment = this.loanAmount * 10000 * 
          (monthlyRate * Math.pow(1 + monthlyRate, totalMonths)) / 
          (Math.pow(1 + monthlyRate, totalMonths) - 1)
        return Math.round(monthlyPayment)
      } else {
        // 等额本金首月还款
        const firstMonthInterest = this.loanAmount * 10000 * monthlyRate
        const monthlyPrincipal = this.loanAmount * 10000 / totalMonths
        return Math.round(firstMonthInterest + monthlyPrincipal)
      }
    },
    // 总利息（万元）
    totalInterest() {
      const totalMonths = this.loanYears * 12
      const totalPayment = (this.monthlyPayment * totalMonths) / 10000
      return Math.round((totalPayment - this.loanAmount) * 10) / 10
    },
    // 还款总额（万元）
    totalPayment() {
      return Math.round((this.loanAmount + this.totalInterest) * 10) / 10
    }
  },
  watch: {
    housePrice() { this.calculateMortgage() },
    downPaymentPercent() { this.calculateMortgage() },
    loanYears() { this.calculateMortgage() },
    interestRate() { this.calculateMortgage() },
    repaymentMethod() { this.calculateMortgage() }
  },
  mounted() {
    this.calculateMortgage()
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    calculateMortgage() {
      this.generatePaymentSchedule()
    },
    generatePaymentSchedule() {
      this.paymentSchedule = []
      const monthlyRate = this.interestRate / 100 / 12
      const totalMonths = this.loanYears * 12
      const loanAmountYuan = this.loanAmount * 10000
      
      if (this.repaymentMethod === 'equal-principal-interest') {
        // 等额本息
        const monthlyPayment = this.monthlyPayment
        let remainingPrincipal = loanAmountYuan
        
        for (let i = 1; i <= totalMonths; i++) {
          const interestPayment = remainingPrincipal * monthlyRate
          const principalPayment = monthlyPayment - interestPayment
          remainingPrincipal -= principalPayment
          
          this.paymentSchedule.push({
            period: i,
            monthlyPayment: monthlyPayment.toFixed(0),
            principal: principalPayment.toFixed(0),
            interest: interestPayment.toFixed(0),
            remaining: Math.max(0, remainingPrincipal).toFixed(0)
          })
        }
      } else {
        // 等额本金
        const monthlyPrincipal = loanAmountYuan / totalMonths
        let remainingPrincipal = loanAmountYuan
        
        for (let i = 1; i <= totalMonths; i++) {
          const interestPayment = remainingPrincipal * monthlyRate
          const monthlyPayment = monthlyPrincipal + interestPayment
          remainingPrincipal -= monthlyPrincipal
          
          this.paymentSchedule.push({
            period: i,
            monthlyPayment: monthlyPayment.toFixed(0),
            principal: monthlyPrincipal.toFixed(0),
            interest: interestPayment.toFixed(0),
            remaining: Math.max(0, remainingPrincipal).toFixed(0)
          })
        }
      }
    },
    toggleSchedule() {
      this.showSchedule = !this.showSchedule
    }
  }
}
</script>

<style scoped>
.mortgage-calculator {
  background: #fafafa;
  min-height: 100vh;
  padding-bottom: 20px;
}

.detail-header {
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 100;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  align-items: center;
  padding: 12px 16px;
}

.back-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: background 0.3s;
  margin-right: 12px;
}

.back-btn:hover {
  background: #f5f5f5;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
}

.calculator-container {
  padding: 16px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 0 4px;
}

.section-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  position: relative;
  padding-left: 12px;
}

.section-header h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.input-section, .result-section, .schedule-section, .rate-reference {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-item label {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.percent-display {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #667eea;
  margin-top: 8px;
}

.loan-amount {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  padding: 8px 0;
}

.result-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.result-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  transition: transform 0.3s;
}

.result-card:hover {
  transform: translateY(-2px);
}

.result-icon {
  font-size: 24px;
  color: #667eea;
  margin-bottom: 8px;
}

.result-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.result-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.schedule-table {
  margin-top: 16px;
}

.schedule-tip {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin-top: 12px;
}

.rate-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.rate-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.rate-type {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.rate-value {
  font-size: 16px;
  font-weight: bold;
  color: #667eea;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

@media (max-width: 768px) {
  .result-cards {
    grid-template-columns: 1fr;
  }
  
  .rate-cards {
    grid-template-columns: 1fr;
  }
}
</style>